﻿using Help.Library.Help;
using Newtonsoft.Json;
using SmallTool.Entity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SmallTool.frm
{
    public partial class frm_modify : Form
    {
        public frm_modify()
        {
            InitializeComponent();
        }

        string str_CConn = string.Empty;
        string str_UConn = string.Empty;
        bool isVerConn = false;
        bool isVerData = false;
        List<string> cDataBaseList = new List<string>();
        List<string> uDataBaseList = new List<string>();
        bool isModifyType = false; // false=>单号;true=>双号互换
        List<TempModify> IPList = new List<TempModify>();
        Dictionary<string, string> sdkDic = new Dictionary<string, string>();

        private void btn_TestLink_Click(object sender, EventArgs e)
        {
            string str_CIP = cmb_CIP.Text.Trim();
            string str_CloginName = txt_CLoginName.Text.Trim();
            string str_Cpwd = txt_CPwd.Text.Trim();
            string str_CDataBaseName = cmb_CDataBaseName.Text.Trim();
            if (string.IsNullOrWhiteSpace(str_CIP) || string.IsNullOrWhiteSpace(str_CloginName)
                || string.IsNullOrWhiteSpace(str_Cpwd) || string.IsNullOrWhiteSpace(str_CDataBaseName))
            {
                MessageBox.Show("请输入完整的用户中心库链接信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            string str_UIP = cmb_UIP.Text.Trim();
            string str_UloginName = txt_ULoginName.Text.Trim();
            string str_Upwd = txt_UPwd.Text.Trim();
            string str_UDataBaseName = cmb_UDataBaseName.Text.Trim();
            if (string.IsNullOrWhiteSpace(str_UIP) || string.IsNullOrWhiteSpace(str_UloginName)
                || string.IsNullOrWhiteSpace(str_Upwd) || string.IsNullOrWhiteSpace(str_UDataBaseName))
            {
                MessageBox.Show("请输入完整的用户信息库链接信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            try
            {
                #region 验证中心库链接是否正确
                string str_sql = string.Format(@"select SCHEMA_NAME from information_schema.SCHEMATA ;");
                str_CConn = string.Format("Server={0};Database=mysql;Uid={1};Pwd={2};", str_CIP, str_CloginName, str_Cpwd);
                bool isExists = false;
                string tempValue = string.Empty;
                using (MySql.Data.MySqlClient.MySqlDataReader sdr = MySql.Data.MySqlClient.MySqlHelper.ExecuteReader(str_CConn, str_sql))
                {
                    cDataBaseList.Clear();
                    while (sdr.Read())
                    {
                        tempValue = Convert.ToString(sdr["SCHEMA_NAME"]);
                        if (!isExists) isExists = string.IsNullOrWhiteSpace(tempValue) ? false : true;
                        cDataBaseList.Add(tempValue);
                    }
                }
                if (!isExists)
                {
                    isVerConn = false;
                    pic_C.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"Image\no.png"));
                }
                else
                {
                    isVerConn = true;
                    pic_C.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"Image\yes.png"));
                    cmb_CDataBaseName.DataSource = null;
                    cmb_CDataBaseName.DataSource = cDataBaseList;
                }
                #endregion

                #region 验证用户库链接是否正确
                str_UConn = string.Format("Server={0};Database=mysql;Uid={1};Pwd={2};", str_UIP, str_UloginName, str_Upwd);
                isExists = false;
                using (MySql.Data.MySqlClient.MySqlDataReader sdr = MySql.Data.MySqlClient.MySqlHelper.ExecuteReader(str_UConn, str_sql))
                {
                    uDataBaseList.Clear();
                    while (sdr.Read())
                    {
                        tempValue = Convert.ToString(sdr["SCHEMA_NAME"]);
                        if (!isExists) isExists = string.IsNullOrWhiteSpace(tempValue) ? false : true;
                        uDataBaseList.Add(tempValue);
                    }
                }
                if (!isExists)
                {
                    if (isVerConn)
                        isVerConn = false;
                    pic_U.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"Image\no.png"));
                }
                else
                {
                    if (isVerConn)
                        isVerConn = true;
                    pic_U.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"Image\yes.png"));
                    cmb_UDataBaseName.DataSource = null;
                    cmb_UDataBaseName.DataSource = uDataBaseList;
                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void frm_modify_Load(object sender, EventArgs e)
        {
            pic_C.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"Image\t.png"));
            pic_U.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"Image\t.png"));
            pic_C_1.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"Image\t.png"));
            pic_C_2.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"Image\t.png"));
            pic_U_1.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"Image\t.png"));
            pic_U_2.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"Image\t.png"));

            string settingPath = string.Format(@"{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"setting\ModifyAddress.txt");
            using (StreamReader sr = new StreamReader(settingPath, Encoding.Default))
            {
                string line = string.Empty;
                IPList.Clear();
                while (!string.IsNullOrWhiteSpace(line = sr.ReadLine()))
                {
                    string[] arr = line.Split('|');
                    if (arr.Length == 4)
                    {
                        IPList.Add(new TempModify(Convert.ToInt32(arr[0]), Convert.ToString(arr[1]), Convert.ToString(arr[2]), Convert.ToString(arr[3])));
                    }
                }
            }

            cmb_CIP.DataSource = IPList.ToList<TempModify>();
            cmb_CIP.DisplayMember = "IP";
            cmb_CIP.ValueMember = "ID";
            cmb_UIP.DataSource = IPList.ToList<TempModify>();
            cmb_UIP.DisplayMember = "IP";
            cmb_UIP.ValueMember = "ID";

            TempModify tempModel = IPList.Find(o => o.ID == Convert.ToInt32(cmb_CIP.SelectedValue));
            if (tempModel != null)
            {
                txt_CLoginName.Text = tempModel.LoginName;
                txt_ULoginName.Text = tempModel.LoginName;
                txt_CPwd.Text = tempModel.PassWord;
                txt_UPwd.Text = tempModel.PassWord;
            }

            settingPath = string.Format(@"{0}{1}", AppDomain.CurrentDomain.BaseDirectory, @"setting\sdk.txt");
            using (StreamReader sr = new StreamReader(settingPath, Encoding.Default))
            {
                string line = string.Empty;
                sdkDic.Clear();
                while (!string.IsNullOrWhiteSpace(line = sr.ReadLine()))
                {
                    string[] arr = line.Split('|');
                    if (arr.Length == 2)
                    {
                        if (!sdkDic.ContainsKey(arr[0].ToString()))
                        {
                            sdkDic.Add(arr[0].ToString(), arr[1].ToString());
                        }
                    }
                }
                if (sdkDic.Count > 0)
                {
                    BindingSource bs = new BindingSource();
                    bs.DataSource = sdkDic;
                    cmb_sdkType.DataSource = bs;
                    cmb_sdkType.DisplayMember = "value";
                    cmb_sdkType.ValueMember = "key";
                }
            }
        }

        private void UpdateTextState()
        {
            isModifyType = rdo_Two.Checked;
            txt_CUID_2.Enabled = isModifyType;
            txt_URid_2.Enabled = isModifyType;
        }

        private void rdo_Two_Click(object sender, EventArgs e)
        {
            UpdateTextState();
        }

        private void btn_VerUserData_Click(object sender, EventArgs e)
        {
            if (!isVerConn)
            {
                MessageBox.Show("数据库链接验证未通过", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string str_CUID_1 = txt_CUID_1.Text.Trim();
            string str_CServerId = txt_CServerId.Text.Trim();
            string str_CUID_2 = txt_CUID_1.Text.Trim();
            if (string.IsNullOrWhiteSpace(str_CUID_1) || string.IsNullOrWhiteSpace(str_CServerId))
            {
                MessageBox.Show("请输入完整的中心库_1数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (isModifyType)
            {
                if (string.IsNullOrWhiteSpace(str_CUID_2))
                {
                    MessageBox.Show("请输入完整的中心库_2数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            string str_URid_1 = txt_URid_1.Text.Trim();
            string str_UServerId = txt_UServerId.Text.Trim();
            string str_URid_2 = txt_URid_2.Text.Trim();
            if (string.IsNullOrWhiteSpace(str_URid_1) || string.IsNullOrWhiteSpace(str_UServerId))
            {
                MessageBox.Show("请输入完整的用户库_1数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (isModifyType)
            {
                if (string.IsNullOrWhiteSpace(str_URid_2))
                {
                    MessageBox.Show("请输入完整的用户库_2数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            isVerData = false;
            bool isError = false;
            string str_CSql = string.Format(@"select Rid from {0}.game_role where uid={1} and ServerId={2}", cmb_CDataBaseName.Text.Trim(), str_CUID_1, str_CServerId);
            using (MySql.Data.MySqlClient.MySqlDataReader sdr = MySql.Data.MySqlClient.MySqlHelper.ExecuteReader(str_CConn, str_CSql))
            {
                while (sdr.Read())
                {
                    txt_CRid_1.Text = Convert.ToString(sdr["Rid"]);
                    isVerData = true;
                    isError = true;
                }
                pic_C_1.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, isError ? @"Image\yes.png" : @"Image\no.png"));
            }
            if (isModifyType)
            {
                isError = false;
                str_CSql = string.Format(@"select Rid from {0}.game_role where uid={1} and ServerId={2}", cmb_CDataBaseName.Text.Trim(), str_CUID_2, str_CServerId);
                using (MySql.Data.MySqlClient.MySqlDataReader sdr = MySql.Data.MySqlClient.MySqlHelper.ExecuteReader(str_CConn, str_CSql))
                {
                    while (sdr.Read())
                    {
                        txt_CRid_2.Text = Convert.ToString(sdr["Rid"]);
                        if (isVerData) isVerData = true;
                        isError = true;
                    }
                    pic_C_2.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, isError ? @"Image\yes.png" : @"Image\no.png"));
                }
            }

            string str_USql = string.Format(@"select Uid from {0}.user_role where Rid={1} and ServerId={2}", cmb_UDataBaseName.Text.Trim(), str_URid_1, str_UServerId);
            using (MySql.Data.MySqlClient.MySqlDataReader sdr = MySql.Data.MySqlClient.MySqlHelper.ExecuteReader(str_UConn, str_USql))
            {
                isError = false;
                while (sdr.Read())
                {
                    txt_UUID_1.Text = Convert.ToString(sdr["Uid"]);
                    if (isVerData) isVerData = true;
                    isError = true;
                }
                pic_U_1.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, isError ? @"Image\yes.png" : @"Image\no.png"));
            }
            if (isModifyType)
            {
                isError = false;
                str_USql = string.Format(@"select Uid from {0}.user_role where Rid={1} and ServerId={2}", cmb_UDataBaseName.Text.Trim(), str_URid_2, str_UServerId);
                using (MySql.Data.MySqlClient.MySqlDataReader sdr = MySql.Data.MySqlClient.MySqlHelper.ExecuteReader(str_UConn, str_USql))
                {
                    while (sdr.Read())
                    {
                        txt_UUID_2.Text = Convert.ToString(sdr["Uid"]);
                        if (isVerData) isVerData = true;
                        isError = true;
                    }
                    pic_U_2.Load(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, isError ? @"Image\yes.png" : @"Image\no.png"));
                }
            }

            if (!isVerData)
            {
                MessageBox.Show("用户数据存在错误,请检查后重试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        private void btn_Modify_Click(object sender, EventArgs e)
        {
            if (!isVerConn && !isVerData)
            {
                MessageBox.Show("验证未通过", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string str_sdk = cmb_sdkType.SelectedValue.ToString();
            string str_serverId = txt_Modify_ServerId.Text.Trim();
            if (string.IsNullOrWhiteSpace(str_sdk) || string.IsNullOrWhiteSpace(str_serverId))
            {
                MessageBox.Show("请输入改号玩家的渠道号和服务器分组编号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (!isModifyType)
            {
                try
                {
                    // 修改中心库Rid
                    string str_CSql_Modify = string.Format(@"update {0}.game_role set Rid={1} where Uid={2} and ServerId={3}", cmb_CDataBaseName.Text.Trim(), txt_URid_1.Text.Trim(), txt_CUID_1.Text.Trim(), txt_CServerId.Text.Trim());
                    MySql.Data.MySqlClient.MySqlHelper.ExecuteNonQuery(str_CConn, str_CSql_Modify);

                    // 修改用户库UID,SDK,ServerID
                    string str_USql_Modify = string.Format(@"update {0}.user_role set Uid={1},SdkType={2},ServerId={3},ServerGroup={3} where Rid={4}", cmb_UDataBaseName.Text.Trim(), txt_CUID_1.Text.Trim(), str_sdk, str_serverId, txt_URid_1.Text.Trim());
                    MySql.Data.MySqlClient.MySqlHelper.ExecuteNonQuery(str_UConn, str_USql_Modify);

                    MessageBox.Show("改号成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.None);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                try
                {
                    int tempRid = Convert.ToInt32(txt_URid_2.Text.Trim()) * 100;
                    // 修改中心库Rid
                    string str_CSql_Modify = string.Format(@"update {0}.game_role set Rid={1} where Uid={2} and ServerId={3}", cmb_CDataBaseName.Text.Trim(), tempRid, txt_CUID_1.Text.Trim(), txt_CServerId.Text.Trim());
                    MySql.Data.MySqlClient.MySqlHelper.ExecuteNonQuery(str_CConn, str_CSql_Modify);
                    str_CSql_Modify = string.Format(@"update {0}.game_role set Rid={1} where Uid={2} and ServerId={3}", cmb_CDataBaseName.Text.Trim(), txt_URid_1.Text.Trim(), txt_CUID_2.Text.Trim(), txt_CServerId.Text.Trim());
                    MySql.Data.MySqlClient.MySqlHelper.ExecuteNonQuery(str_CConn, str_CSql_Modify);
                    str_CSql_Modify = string.Format(@"update {0}.game_role set Rid={1} where Uid={2} and ServerId={3}", cmb_CDataBaseName.Text.Trim(), tempRid / 100, txt_CUID_1.Text.Trim(), txt_CServerId.Text.Trim());
                    MySql.Data.MySqlClient.MySqlHelper.ExecuteNonQuery(str_CConn, str_CSql_Modify);

                    int tempUid = Convert.ToInt32(txt_CUID_2.Text.Trim()) * 100;
                    // 修改用户库UID,SDK,ServerID
                    string str_USql_Modify = string.Format(@"update {0}.user_role set Uid={1},SdkType={2},ServerId={3},ServerGroup={3} where Rid={4}", cmb_UDataBaseName.Text.Trim(), tempUid, str_sdk, str_serverId, txt_URid_1.Text.Trim());
                    MySql.Data.MySqlClient.MySqlHelper.ExecuteNonQuery(str_UConn, str_USql_Modify);
                    str_USql_Modify = string.Format(@"update {0}.user_role set Uid={1},SdkType={2},ServerId={3},ServerGroup={3} where Rid={4}", cmb_UDataBaseName.Text.Trim(), txt_CUID_1.Text.Trim(), str_sdk, str_serverId, txt_URid_2.Text.Trim());
                    MySql.Data.MySqlClient.MySqlHelper.ExecuteNonQuery(str_UConn, str_USql_Modify);
                    str_USql_Modify = string.Format(@"update {0}.user_role set Uid={1},SdkType={2},ServerId={3},ServerGroup={3} where Rid={4}", cmb_UDataBaseName.Text.Trim(), tempUid / 100, str_sdk, str_serverId, txt_URid_1.Text.Trim());
                    MySql.Data.MySqlClient.MySqlHelper.ExecuteNonQuery(str_UConn, str_USql_Modify);

                    MessageBox.Show("改号成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.None);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void cmb_CIP_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cmb_CIP.SelectedValue != null)
            {
                string str_id = cmb_CIP.SelectedValue.ToString();
                int id = 0;
                if (Int32.TryParse(str_id, out id))
                {
                    TempModify tempModel = IPList.Find(o => o.ID == Convert.ToInt32(str_id));
                    if (tempModel != null)
                    {
                        txt_CLoginName.Text = tempModel.LoginName;
                        txt_CPwd.Text = tempModel.PassWord;
                    }
                }
            }
        }

        private void cmb_UIP_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cmb_UIP.SelectedValue != null)
            {
                string str_id = cmb_UIP.SelectedValue.ToString();
                int id = 0;
                if (Int32.TryParse(str_id, out id))
                {
                    TempModify tempModel = IPList.Find(o => o.ID == Convert.ToInt32(str_id));
                    if (tempModel != null)
                    {
                        txt_ULoginName.Text = tempModel.LoginName;
                        txt_UPwd.Text = tempModel.PassWord;
                    }
                }
            }
        }
    }
}